package com.feng.cloud.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.feng.cloud.common.exception.SystemException;
import com.feng.cloud.common.exception.auth.AuthStatus;
import com.feng.cloud.common.exception.system.ParameterException;
import com.feng.cloud.common.exception.system.SystemStatus;
import com.feng.cloud.common.request.QueryRequest;
import com.feng.cloud.common.response.RestResponse;
import com.feng.cloud.common.response.TableResultResponse;
import com.feng.cloud.system.entity.Todo;
import com.feng.cloud.system.service.TodoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @ClassName TodoController
 * @Description TODO
 * @Author Better Feng
 * @Date 2020/1/5 16:49
 * @Version 1.0
 **/
@Slf4j
@Validated
@RequestMapping("todo")
@RestController
@RequiredArgsConstructor
public class TodoController {

    private final TodoService todoService;

    @PostMapping
    public RestResponse<Todo> addTodo(@Valid Todo todo, Principal principal) {
        String name = principal.getName();
        if (StringUtils.isBlank(name)) {
            throw new AccessDeniedException(AuthStatus.USER_FORBIDDEN.getMessage());
        }
        todo.setUsername(name);
        todo.setCreateTime(LocalDateTime.now());
        todoService.save(todo);
        return new RestResponse<Todo>().data(todo);
    }

    @PutMapping
    public RestResponse<Todo> updateTodo(@Valid Todo todo, Principal principal) {
        Long id = todo.getId();
        if (id == null) {
            throw new ParameterException(SystemStatus.ID_EMPTY);
        }
        LambdaQueryWrapper<Todo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Todo::getId, id);
        queryWrapper.eq(Todo::getUsername, principal.getName());
        boolean update = todoService.update(todo, queryWrapper);
        if (update) {
            return new RestResponse<Todo>().data(todo);
        }
        throw new SystemException(SystemStatus.UPDATE_FAILED);
    }

    @DeleteMapping("{id}")
    public RestResponse<Void> deleteTodo(@PathVariable Long id) {
        todoService.removeById(id);
        return new RestResponse<>();
    }

    @GetMapping("/page")
    public TableResultResponse<Todo> selectByPage(@RequestParam Map<String, Object> params) {
        QueryRequest request = new QueryRequest(params);
        IPage<Todo> iPage = todoService.selectListByPage(request);
        return new TableResultResponse<>(iPage.getTotal(), iPage.getRecords());
    }

}
